package com.lkx.farmershop.controller;


import com.lkx.farmershop.common.api.ApiResult;
import com.lkx.farmershop.model.dto.LocationDto;
import com.lkx.farmershop.model.dto.LoginDTO;
import com.lkx.farmershop.model.entity.Farmer;
import com.lkx.farmershop.service.IFarmerService;
import com.lkx.farmershop.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lkx
 * @since 2024-02-05
 */
@RestController
@RequestMapping("/farmer")
@Slf4j
public class FarmerController {

    @Autowired
    private IFarmerService farmerService;

    @PostMapping("/register")
    private ApiResult<String> executeRegister(@RequestBody Farmer farmer){
        String message=farmerService.executeRegister(farmer);
        return ApiResult.success(message);
    }


    @GetMapping("/sendMsg")
    public ApiResult<String> sendMsg(String phoneNum) {
        //获取手机号
        String phone = phoneNum;

        //生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        //调用阿里云提供的短信服务API完成发送短信
        // SMSUtils.sendMessage("瑞吉外卖","SMS_283475471",phone,code);

        //需要将生成的验证码保存到Session

        return ApiResult.success(code);

    }

    @PostMapping("/login")
    public ApiResult<Map<String, String>> login(@RequestBody LoginDTO dto) {
        String token = farmerService.executeLogin(dto);
        if (ObjectUtils.isEmpty(token)) {
            return ApiResult.failed("账号密码错误");
        }
        Map<String, String> map = new HashMap<>(16);
        Farmer one = farmerService.lambdaQuery().eq(Farmer::getPhoneNum, dto.getPhoneNum()).one();

        log.info("token: {}", token);

        map.put("token", token);
        map.put("avatar",one.getAvatar());
        map.put("name",one.getName());
        map.put("userId", one.getFarmerId().toString());
        map.put("location",one.getLocation());
        map.put("longitude", String.valueOf(one.getLongitude()));
        map.put("latitude", String.valueOf(one.getLatitude()));
        return ApiResult.success(map, "登录成功");
    }

    /**
     * 更新用户位置
     * @param locationDto
     * @return
     */
    @PutMapping("/updateLocation")
    public ApiResult<String> updateLocation(@RequestBody LocationDto locationDto){
        return farmerService.updateLocation(locationDto);
    }
}
